import { response } from "express";
import { request } from "express";
import { CheckToken, CreateToken } from '../util/Token.js'
/**
 * @Author HuiLY
 * @Date 2023-03-27 22:12:41
 * @param {response} res
 * @param {request} req
 * @ token验证
 */
async function CheckTokenWare(req, res, next) {
    try {
        const regExp = /^\/((upload)|(static)|(login)|(register)|(base)){1}(\/.*)*$/;
        if (regExp.test(req.url)) {
            res.setHeader('token', await CreateToken())
            next()
            return
        } else {
            const authorization = req.headers['authorization'];
            if (authorization && authorization.length) {
                const token = authorization.split(' ')[1];
                let { status } = await CheckToken(token);
                if (token && token.length && status) {
                    res.header('token', await CreateToken())
                    next()
                } else {
                    res.status(401)
                    res.json({
                        msg: 'token已失效,请重新登录!',
                        code: 401,
                        redirectRouter: {
                            path: '/login'
                        }
                    }).end()
                    return
                }
            } else {
                res.removeHeader('token')
                res.status(401)
                res.json({
                    msg: '没有token,请登录!',
                    code: 401,
                    redirectRouter: {
                        patj: '/login'
                    }
                }).end()
                return;
            }
        }
    } catch (error) {
        next(error)
    }
}

/**
 * @Author HuiLY
 * 后续添加，通过用户的ID生成token
 * @param {response} res
 * @param {request} req
 * @ token生成
 */
async function CreateTokenWare(req, res, next) {
    if (global.$currentUserInfo && global.$currentUserInfo.id && global.$currentUserInfo.id.length) {
        let token = await CreateToken()
    }
}
export default CheckTokenWare;